package other.edan.erp.k3;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.data.model.Product;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.AsyncTaskException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.edan.erp.apitool.EdanK3Utils;
import other.edan.erp.utils.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description 同步K3产品数据
 * @Author 黎炎松
 * 2024-06-19 13:53
 */
@RestApi(baseUrl = "/xsy/product")
public class SyncProduct implements ScheduleJob, FutureTask {
    private static XoqlService xoqlService = XoqlService.instance();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "定时同步K3产品数据 ==> ";

    // 执行定时任务
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        logger.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        startSyncProductData("");
    }

    /**
     * 根据产品编号手动触发产品同步
     * @param
     * @return
     */
    @RestMapping(value = "/syncK3ProductByNumber", method = RequestMethod.POST)
    public String syncK3ProductByNumber(@RestQueryParam(name = "id") Long productId) {

        // 获取产品的编码
        logger.debug("根据产品编号手动触发产品同步: " + productId);
        Product product = new Product();
        product.setId(productId);
        product = HCXObjectService.get(product);
        String fNumber__c = product.getFNumber__c();

        logger.debug("根据产品编号手动触发产品同步: " + fNumber__c);
        return startSyncProductData(fNumber__c);
    }

    /**
     * 手动触发产品同步
     * @param
     * @return
     */
    @RestMapping(value = "/syncK3Product", method = RequestMethod.POST)
    public String syncK3Product() throws AsyncTaskException {
        logger.debug("手动触发产品同步");
        String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
        logger.info(LOGGER_MSG + "异步ID:" + messageId);
        return TfReturnMsgTools.getSuccessResult("开始同步数据");
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        SyncProduct syncProduct = new SyncProduct();
        syncProduct.startSyncProductData("");
    }

    /**
     * 开始同步产品数据
     * @param productNumber 多个产品使用道号分割
     * @return
     */
    public String startSyncProductData(String productNumber) {
        try {
            logger.debug(LOGGER_MSG + "处理开始");

            // 从数据配置表中获取数据
            String sql = "select id,lastSyncTime__c,syncAssistVal__c from syncConfig__c where syncKey__c = 'K3_CPTB'";
            SyncConfig__c syncConfig = HCXObjectService.queryOne(sql);
            logger.debug(LOGGER_MSG + " syncConfig = " + syncConfig);
            if (syncConfig == null) {
                logger.debug(LOGGER_MSG + " 数据配置信息不存在");
                return TfReturnMsgTools.getFailResult("数据配置信息不存在");
            }

            // 获取同步时间
            String startDate = syncConfig.getLastSyncTime__c();
            String endDate = HCDateUtils.dateToString(new Date(), HCDateUtils.FORMATTIME); // 同步结束时间
            if (StringUtils.isBlank(startDate)) {
                // 如果为空则退回1天前
                startDate = HCDateUtils.getDaysBeforeString(1, HCDateUtils.FORMATTIME);
            }
            //startDate = "2020-01-18 00:00:00";
            //endDate = "2025-03-07 00:00:00";

            // 设置参数
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", "1");
            paramsMap.put("pageSize", "3000");
            // 产品编码如果不为空 则只入参产品编码
            if (StringUtils.isNotBlank(productNumber)) {
                paramsMap.put("productNumber", productNumber);
            } else {
                paramsMap.put("updateStartDate", startDate);
                paramsMap.put("updateEndDate", endDate);
            }
            logger.debug(LOGGER_MSG + " paramsMap: " + paramsMap);


            // 发送请求获取数据
            ResultBody response = EdanK3Utils.sendGet(paramsMap, EdanK3Utils.GET_PRODUCT_URL, "");
            if (!Objects.equals(response.getCode(), "200")) {
                logger.debug(LOGGER_MSG + "查询k3产品数据异常: " + response.getMessage());
                return TfReturnMsgTools.getFailResult("查询k3产品数据异常: " + response.getMessage());
            }

            // 获取产品数据 判断是否有值
            JSONObject result = (JSONObject) response.getResult();
            List<JSONObject> productList = JSONObject.parseArray(result.getJSONArray("productInfos").toJSONString(), JSONObject.class);
            logger.debug(LOGGER_MSG + "查询返回的数据: " + productList.size());
            if (productList.size() <= 0) {
                logger.debug(LOGGER_MSG + "暂无需要处理的数据");
                // 同步修改配置表
                syncConfig.setLastSyncTime__c(endDate);
                syncConfig.setLastSyncCount__c(0L);
                HCXObjectService.update(syncConfig);
                return TfReturnMsgTools.getSuccessResult("暂无需要同步的产品");
            }


            // 获取选项通用集以及产品目录数据
            JSONArray unitPickList = ComUtils.getGlobalPicks("globalPick37__c"); // 单位
            JSONArray productLinePick = ComUtils.getGlobalPicks("globalPick53__c"); // ERP产品线

            sql = "select id,name,productIine__c from K3Mapping__c where entityType = 3344173148002968";
            List<JSONObject> k3MappingList = xoqlService.query(sql, true).getRecords();

            // 获取系统中的产品数据 判断是否已经存在
            String fnumbers = productList.stream().map(v -> "'" + v.getString("fnumber") + "'").collect(Collectors.joining(","));
            logger.debug(LOGGER_MSG + "fnumbers: " + fnumbers);
            sql = "select id,FNumber__c,fitemID__c from product where productBelong__c = 1 and FNumber__c in (" + fnumbers + ")";
            QueryResult<JSONObject> productQuery = xoqlService.query(sql, true);
            Map<String, List<JSONObject>> crmProductMap = productQuery.getRecords().stream().collect(Collectors.groupingBy(e -> e.getString("FNumber__c")));
            logger.debug(LOGGER_MSG + "crmProductMap: " + crmProductMap);

            // 获取新增、修改的数据
            List<Product> addProductList = new ArrayList<>();
            List<Product> upProductList = new ArrayList<>();
            for (JSONObject productObj : productList) {
                Product product = new Product();
                product.setEntityType(11010000400001L);
                product.setProductBelong__c(1); // 产品归属 理邦内销
                String f_154 = productObj.getString("f_154");
                String f_105 = productObj.getString("f_105");
                String fnumber = productObj.getString("fnumber");

                product.setF_127__c(productObj.getString("f_127")); // 产品注册名称
                product.setF_134__c(productObj.getString("f_134")); // 产品注册型号
                product.setF_154__c(f_154); // 产品注册证号
                product.setF_155__c(productObj.getString("f_155")); // 生产许可证号
                product.setF_105__c(ComUtils.getValueByApiKey(productLinePick, f_105)); // ERP产品线

                product.setFModel__c(productObj.getString("fmodel")); // 规格型号
                product.setFNumber__c(fnumber); // 物料代码
                product.setProductName(productObj.getString("fname")); // 物料名称
                product.setFitemID__c(productObj.getString("fitemID")); // 产品id

                // 单位
                String funitCode = productObj.getString("funitCode");
                Integer codeVal = ComUtils.getValueByApiKey(unitPickList, funitCode);
                if (codeVal != null) {
                    product.setFCUUnitlD__c(codeVal); // 单位
                }

                // 目录、范围 国械注准20183071555
                if (StringUtils.isNotBlank(f_154)) {
                    f_154 = f_154.replace(" ", ""); // 去除空格
                    try {
                        product.setBusinessCategory__c(Integer.valueOf(f_154.substring(8,9))); // 分类
                        product.setProductClassification__c(Integer.valueOf(f_154.substring(9,11)) + 1); // 范围
                    } catch (Exception e) {
                        logger.error(LOGGER_MSG + "处理目录、范围字段异常 productObj = " + f_154);
                    }
                }

                // 产品目录
                if (StringUtils.isNotBlank(f_105)) {
                    JSONObject mapperObj = k3MappingList.stream().filter(v -> Objects.equals(v.getString("name"), f_105)).findFirst().orElse(null);
                    if (mapperObj != null) {
                        product.setParentId(mapperObj.getLong("productIine__c"));
                    }
                }

                // 判断系统中是否存在，存在则更新
                logger.debug(LOGGER_MSG + "product =" + product);
                if (crmProductMap.containsKey(fnumber)) {
                    Long productId = crmProductMap.get(fnumber).get(0).getLong("id");
                    product.setId(productId);
                    upProductList.add(product);
                } else {
                    // 新增
                    addProductList.add(product);
                }

                // 进行新增、更新
                if (addProductList.size() > 100) {
                    HCXObjectService.insertBatch(addProductList);
                    HCXObjectService.insertBatch(addProductList);
                    addProductList.clear();
                }
                if (upProductList.size() > 100) {
                    HCXObjectService.updateBatch(upProductList);
                    upProductList.clear();
                }

            }


            // 批量新增
            if (addProductList.size() > 0) {
                logger.debug(LOGGER_MSG + "新增的数据: " + addProductList.size());
                BatchOperateResult batchOperateResult = HCXObjectService.insertBatch(addProductList);
                if (!batchOperateResult.getSuccess()) {
                    logger.debug(LOGGER_MSG + "批量新增异常: " + batchOperateResult.getErrorMessage());
                    //return TfReturnMsgTools.getFailResult("新增异常:"  +batchOperateResult.getErrorMessage());
                }
            }

            // 批量修改
            if (upProductList.size() > 0) {
                logger.debug(LOGGER_MSG + "修改的数据: " + upProductList.size());
                BatchOperateResult batchOperateResult = HCXObjectService.updateBatch(upProductList);
                if (!batchOperateResult.getSuccess()) {
                    logger.debug(LOGGER_MSG + "批量修改异常: " + batchOperateResult.getErrorMessage());
                    //return TfReturnMsgTools.getFailResult("修改异常:"  +batchOperateResult.getErrorMessage());
                }
            }

            // 更新同步配置
            if (StringUtils.isBlank(productNumber)) {
                syncConfig.setLastSyncTime__c(endDate);
                syncConfig.setLastSyncCount__c(Long.valueOf(productList.size()));
                OperateResult update = HCXObjectService.update(syncConfig);
                if (!update.getSuccess()) {
                    logger.debug(LOGGER_MSG + "更新同步配置异常");
                    return TfReturnMsgTools.getFailResult("更新同步配置异常");
                }
            }

            logger.debug(LOGGER_MSG + "处理成功");
            return TfReturnMsgTools.getSuccessResult("同步成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(LOGGER_MSG + "处理异常:" + e.getMessage());
            return TfReturnMsgTools.getFailResult("同步异常:" + e.getMessage());
        }
    }



}
